class Solution
{
public:
    ListNode* sortList(ListNode* head)
    {
        if (!head || !head->next) return head;
        auto slow = head, fast = head;
        while (fast->next && fast->next->next)
            slow = slow->next, fast = fast->next->next;

        fast = slow->next, slow->next = nullptr;
        return merge(sortList(head), sortList(fast));
    }
private:
    ListNode* merge(ListNode* l1, ListNode* l2)
    {
        ListNode dummy(0), * ptr = &dummy;
        while (l1 && l2)
        {
            if (l1->val <= l2->val)
            {
                ptr->next = l1;
                l1 = l1->next;
            }
            else
            {
                ptr->next = l2;
                l2 = l2->next;
            }
            ptr = ptr->next;
        }
        ptr->next = l1 ? l1 : l2;
        return dummy.next;
    }
};